package com.boot.utils;

import io.jsonwebtoken.*;
import lombok.Setter;
import org.springframework.stereotype.Component;

import javax.crypto.SecretKey;
import java.util.Date;

@Component
@Setter
public class JwtUtil {
    //过期时间/分钟
    private final Integer tokenExpireTime = 120;
    private static SecretKey tokenSecret;

    static {
        try {
            tokenSecret = CreateHS512Key.getSecretKey();
        } catch (Exception e) {
            throw new ExceptionInInitializerError("Failed to initialize JWT key"+e.getMessage());
        }
    }

    public String createToken(Long userId) {
        Claims claims = Jwts.claims()
                .setSubject(userId.toString())
                .setExpiration(new Date(System.currentTimeMillis() + tokenExpireTime * 60000));
        return Jwts.builder()
                .setClaims(claims)
                .signWith(tokenSecret)
                .compact();
    }

    public Long getUserIdByToken(String token) {
        Claims claims = Jwts.parserBuilder()
                .setSigningKey(tokenSecret)
                .build()
                .parseClaimsJws(token)
                .getBody();
        String subject = claims.getSubject();
        return Long.parseLong(subject);
    }

    public boolean isTokenExpired(String token) {
        try {
            return Jwts.parserBuilder()
                    .setSigningKey(tokenSecret)
                    .build()
                    .parseClaimsJws(token)
                    .getBody()
                    .getExpiration()
                    .before(new Date());
        } catch (Exception e) {
            return true;
        }
    }
}
